package com.learn.security.web;

import com.learn.security.web.filters.VerifyAuthenticationDetailsSource;
import com.learn.security.web.filters.VerifyAuthenticationProvider;
import com.learn.security.web.security.AdminPermissionEvaluator;
import com.learn.security.web.security.LoginAuthenticationFailureHandler;
import com.learn.security.web.security.LoginAuthenticationSuccessHandler;
import com.learn.security.web.security.LoginExpiredSessionStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @auther liuhw
 * @date 2020/3/16 15:04
 * @description:
 * @since 1.0
 **/
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private VerifyAuthenticationDetailsSource authenticationDetailsSource;

    @Autowired
    private VerifyAuthenticationProvider authenticationProvider;

    @Autowired
    private LoginAuthenticationSuccessHandler successHandler;

    @Autowired
    private LoginAuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/", "/home", "/getVerifyCode", "/login/invalid").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
//                .defaultSuccessUrl("/")
                .permitAll()
//                .failureUrl("/login/error")
                .authenticationDetailsSource(authenticationDetailsSource)
                .and()
//            .addFilterBefore(new VerifyFilter(), UsernamePasswordAuthenticationFilter.class)
            .logout()
//                .logoutUrl("/logout")
                .permitAll()
                .and()
            .rememberMe()
//            .rememberMeParameter("remember-me")
            .tokenRepository(persistentTokenRepository())
            // 有效时间 单位:s
            .tokenValiditySeconds(30).userDetailsService(userDetailsService)
            .and()
            .sessionManagement()
                .invalidSessionUrl("/login/invalid")
                .maximumSessions(1) //单个用户只有一个Session
                .maxSessionsPreventsLogin(true) //当达到最大值时，是否保留已登录的用户
                .expiredSessionStrategy(new LoginExpiredSessionStrategy()) //当达到最大值时, 就用户被踢出的操作
                .sessionRegistry(sessionRegistry())
        ;

        // 关闭csrf跨域
        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
//        auth.userDetailsService(userDetailsService);
//        auth.inMemoryAuthentication()
//                .passwordEncoder(NoOpPasswordEncoder.getInstance())
//                .withUser("user").password("password").roles("USER");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        this.configure(auth);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance(); // 当前密码加密实例
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);

        // 自动创建表
//        tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

    @Bean
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new AdminPermissionEvaluator());
        return handler;
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
}
